var ns, toast, actionsheet, WXPhotoPicker;
var app = new Vue({
    el: '#app',
    data: {
        ID:0,
        form: {
            ID: 0,
            StatusDesc: '',
            issuggestion: 0,
            processType: 1,//1-处理2-完工3-回访
            IsInvalidOrder: false,
            RelationIDList: '',
            ServiceType: 1,//1-客服工单 2-投诉建议 3-品控管理 4-审批中心
        },
        FinalServiceTypeID: 1,
        imglist: [],
        maxuploadcount: CONFIG.maxuploadcount,
        type: 1,//1-处理2-完工3-回访
        OrderReaultType: 1,//1 完工关单 2 重新派单
        //评价
        IsOpenPinjia: true,
        formpj: {
            ID: 0,   // 工单ID
            content: '',// 评价内容
            mainrate: 5,// 评价分值
        },
        pjbz: [],
        pjrate: [
            { ID: 1, url: '../image/pj/pj-fcc.png', title: '非常差', },
            { ID: 2, url: '../image/pj/pj-cha.png', title: '差', },
            { ID: 3, url: '../image/pj/pj-yiban.png', title: '一般', },
            { ID: 4, url: '../image/pj/pj-manyi.png', title: '满意', },
            { ID: 5, url: '../image/pj/pj-fcmy.png', title: '非常满意', },
        ],
        //重新派单
        chhooseUserList: [],
        IsEvaluate: true,//value值1支持评价 2不支持评价
    },
    methods: { 
        do_save: function () {
            var that = this;
            var filelist = [];
            for (var i = 0; i < that.imglist.length; i++) {
                filelist.push(that.imglist[i].url);
            }

            //重新指派-接单人员必选
            if(that.OrderReaultType==2&&that.chhooseUserList.length<=0){
                api.toast({
                    msg: '请选择接单人员',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }

            var options={
                action:'savehuifang',
                ID:that.ID,
                HuiFangNote:that.form.StatusDesc,
                AllStart:that.formpj.mainrate,
                RateComment:that.formpj.content,
                StartArr:JSON.stringify(that.pjbz),
                UserList:JSON.stringify(that.chhooseUserList),
                result:that.OrderReaultType,
            };
            // console.log(JSON.stringify(options));
            ns.post(options, function (succeed, data, err) {
                // console.log(JSON.stringify(succeed));
                // console.log(JSON.stringify(data));
                // console.log(JSON.stringify(err));
                if (succeed) {
                    ns.toast('保存成功');
                    api.sendEvent({
                        name: 'customerservicelist_frm',
                    });
                    api.sendEvent({
                        name: 'reloadservicelist',
                    });
                    api.sendEvent({
                        name: 'updata_task_con',
                        extra: {
                            key1: 'value1'
                        }
                    });
                    setTimeout(function () {
                        api.closeWin();
                    }, 1000);
                } else if (err) {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            }, {
                files: {
                    file: filelist
                },
                toast: true,
                toastmsg: '提交中'
            });
        },
        choose_picture: function () {
            var that = this;
            ns.confirmPer('camera', function () {
                that.choose_picture_start();
            })
        },
        choose_picture_start:function(){
            var that = this;
            if (that.imglist.length >= that.maxuploadcount) {
                api.toast({
                    msg: '最多支持' + that.maxuploadcount + '张图片',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            api.actionSheet({
                cancelTitle: '取消',
                buttons: ['拍照', '从相册选择']
            }, function(ret, err) {
                //拍照
                if(ret.buttonIndex==1){ 
                    that.upload_choose_picture();
                    return;
                }
                //从相册选择
                if(ret.buttonIndex==2){
                    that.choose_picture_album();
                    return;
                } 
                //取消 
                else{
                    return false;  
                }  
            });
        },
        upload_choose_picture:function(){
            var that = this;
            api.getPicture({
                sourceType: 'camera',
                encodingType: 'jpg',
                destinationType: 'url',
                allowEdit: false,
                saveToPhotoAlbum: true,
            }, function(ret, err) {
                if (ret&&ret.data) {
                    that.do_imageFilter(ret.data);
                    // that.imglist.push({
                    //     ID: 0,
                    //     url: ret.data,
                    //     thumbPath: ret.data,
                    //     isupload: true
                    // });
                } 
            });
        },
        choose_picture_album:function(){
            var that = this;
            WXPhotoPicker.open({
                max: that.maxuploadcount - that.imglist.length,
                type:'image',
            }, function(ret) {
                if (ret) {
                    if (ret.list.length > 0) {
                        ret.list.forEach((item) => {
                            that.do_imageFilter(item.path);
                            // that.imglist.push({
                            //     ID: 0,
                            //     url: item.path,
                            //     thumbPath: item.path,
                            //     isupload: true
                            // });
                        });
                    }
                }
            });
        },
         //图片压缩
         do_imageFilter:function(path){
            var that=this;
            var imgName = Date.now() + '.jpg';
            var target_w = 500;
            var imageFilter = api.require('imageFilter');
            imageFilter.getAttr({
                path: path
            }, function(ret, err) {
                if (ret.status) {
                    if (ret.width < target_w) {
                        target_w = ret.width;
                    }
                    var original_w = ret.width;
                    var original_h = ret.height;
                    var scale = original_w / target_w;
                    var target_h = Math.round(original_h / scale);
                    imageFilter.compress({
                        img: path,
                        quality: 1,
                        size: {
                            w: target_w,
                            h: target_h
                        },
                        save: {
                            album: false,
                            imgPath: api.cacheDir + '/upload/',
                            imgName: imgName
                        }
                    }, function(ret, err) {
                        if (ret.status) {
                            var imgFullName=api.cacheDir + '/upload/' + imgName;
                            that.imglist.push({
                                ID: 0,
                                url: imgFullName,
                                thumbPath: imgFullName,
                                isupload: true
                            });
                        }else{
                            alert( JSON.stringify( err ) );
                        }
                    });
                }
            });
        },
        remove_img: function (index,item) {
            var that = this;
            that.imglist.splice(index, 1);
        },
        do_viewimages: function (activeIndex) {
            var that = this;
            var imageUrls = [];
            for (var i = 0; i < that.imglist.length; i++) {
                imageUrls.push(that.imglist[i].url);
            }
            var imageBrowser = api.require('imageBrowser');
            imageBrowser.openImages({
                showList: false,
                activeIndex: activeIndex,
                imageUrls: imageUrls
            });
        },
        //评价
        //评价-获取分类评价标准
        get_pinjia: function () {
            var that = this;
            var options = {
                action: 'getscorecriterionslistserviceid',
                ServiceID: that.ID,
                Type:that.form.ServiceType,
            };
            ns.post(options, function (succeed, data, err) {
                if (succeed) {
                    let pjbzList = data.data || [];
                    that.formpj.mainrate=data.AllStart;
                    that.formpj.content=data.RateComment;
                    that.IsOpenPinjia=data.CanAllStar;
                    that.pjbz = pjbzList;
                    //是否显示评价
                    if (data.IsEvaluate != undefined) {
                        that.IsEvaluate = !data.IsEvaluate? false : true;
                    }
                    return;
                } else if (err) {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                    return;
                }
            });
        },
        do_rate: function (index) {
            var that = this;
            that.formpj.mainrate = index;
        },
        do_rateother: function (index, type) {
            var that = this;
            that.pjbz[type].StartNum = index;
        },
        //重新派单-接单人员
        doReChooseUser: function () {
            var that = this;
            ns.openWin('chooseserviceuser_frm', '重新派单', {
                source: 'transfer',
                id: that.ID,
                type: 7,//1-派单 2-工单转移 3-工单协同 4-重派 5-审批 6-抄送 7回访重新派单
                ServiceType: that.form.ServiceType,
            });
        },
        //移除接单人员
        guanbi_pic: function (id) {
            var that = this;
            that.chhooseUserList = that.chhooseUserList.filter((item) => {
                return item.userID != id
            });
        },
        //查看全部接单人员
        open_more: function () {
            var that = this;
            ns.openWin('renwugongdan_Allperson', '全部接单人员', {
                title:'重新派单',
                source: 'transfer',
                list: that.chhooseUserList,
                id: that.ID,
                type: 7,
                ServiceType: that.form.ServiceType,
            });
        },
    }
});

apiready = function () {
    ns = window.Foresight.Util;
    toast = new auiToast();
    actionsheet = new auiActionsheet();
    WXPhotoPicker = api.require('WXPhotoPicker');
    app.ID = api.pageParam.id || 0;
    app.form.processType = api.pageParam.type;
    app.form.issuggestion = api.pageParam.issuggestion || 0;
    app.form.ServiceType = api.pageParam.ServiceType || 1;

    app.get_pinjia();//获取评分标准

    api.addEventListener({
        name: 'purchase_add'
    }, function (ret) {
        //map字段
        let returnlist = ret.value.data;
        returnlist = returnlist.map(res => {
            res.UserID = res.userID;
            res.UserName = res.realName;
            return res
        })

        //去重
        var chooseposList = app.chhooseUserList;
        chooseposList = chooseposList.concat(returnlist);
        var new_list = chooseposList.filter(function (element, index, self) {
            return self.findIndex(el => el.userID == element.userID) === index  //如果是根据name去重就江id改为name
        })
        app.chhooseUserList = new_list;
    });

    api.addEventListener({
        name: 'purchase_update'
    }, function (ret) {
        //map字段
        let returnlist = ret.value.data;
        app.chhooseUserList=returnlist;
    })

}
